﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using EquationsBankSite.Models.Helpers;
using EquationsBankSite.Models;
using EquationsBankReader.EquationsRead;
using DatabaseModule;
//using EquationsBankReader.DatabaseStructure;

namespace EquationsBankSite
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private EquationsDBEntities entities = new EquationsDBEntities();

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            Application["Fields"] = BuildFieldsTree();
        }

        private TreeNode<string> BuildFieldsTree()
        {
            var root = new TreeNode<string>();
            var tree = from pathLang in entities.Equation_Path_Language
                       join path in entities.Equation_Path
                       on pathLang.Equation_Path equals path
                       join lang in entities.Equation_Name_Language
                       on path.Equation equals lang.Equation_Name.Equation
                       where lang.Name == "V_Equation_00101" && pathLang.Name == "V_Equation_00002"
                       select new { pathLang, lang };

            foreach (var node in tree)
            {
                var parts = node.pathLang.Value.Split('/');
                var currnode = root;
                for (int i = 0; i < parts.Length; i++)
                {
                    var nextnode = currnode.Children.Where(c => c.Data == parts[i]).SingleOrDefault();
                    if (nextnode == null)
                    {
                        nextnode = new TreeNode<string> { Data = parts[i], Parent = currnode };
                        currnode.Children.Add(nextnode);
                    }
                    currnode = nextnode;
                }
                var leaf = new TreeNode<string>
                {
                    Data = node.lang.Value + "@" + node.pathLang.Equation_Path.ID,// .Equation_Path_ID,
                    Parent = currnode
                };
                currnode.Children.Add(leaf);
            }

            return root;
        }
    }
}